#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
"""
import json

import requests
import aiohttp
from aiohttp import ClientSession
from _base.base import BasePage


class SendMsg(object):

    def __init__(self, base_page: BasePage):
        self.base_page = base_page
        self.ws = base_page.ws

    async def send_rate(self, _uuid, rate):
        """
        发送执行百分比
        :param _uuid: 步骤uuid
        :param rate: 进度值
        :return:
        """
        exe_rate = '{"code": 200, "uuid": "%s", "rate": %s}' % (_uuid, rate,)
        if self.base_page.ws:
            await self.ws.send(exe_rate)

    async def custom(self, msg):
        """
        发送自定义消息
        :param msg: 消息内容
        :return:
        """
        if self.base_page.ws:
            await self.ws.send(msg)

    async def send_variables(self):
        """
        发送变量池的数据
        :return:
        """
        var_pool = {
            "全局变量": self.base_page.global_pool,
            "环境变量": self.base_page.env_pool,
            "用例变量": self.base_page.case_pool
        }
        str_var = json.dumps(var_pool, indent=4, ensure_ascii=False)
        msg = f"缓存变量。\n{str_var}"
        await self.base_page.log_info(msg)

    # @staticmethod
    # async def add_test_data(data):
    #     host = "http://192.168.1.109:8000"
    #     # host = "http://autotest.zaxh.cn"
    #     url = f'{host}/api/web/playwrightGridMsg/newStepReport'
    #     result = requests.put(url, json=data).json()
    #     assert result["status"] == 1000

    @staticmethod
    async def add_test_data(data):
        async with aiohttp.ClientSession() as session:  # 使用异步上下文管理器
            addr = "http://yunhai.nat300.top"
            # host = "http://192.168.1.109:8000"
            url = f'{addr}/api/web/playwrightGridMsg/newStepReport'
            async with session.put(url, json=data) as resp:
                result = await resp.json()
                if result["status"] != 1000:
                    raise ValueError(f"Unexpected status: {result['status']}")

    @staticmethod
    async def update_test_report(data):
        addr = "http://yunhai.nat300.top"
        # addr = "http://192.168.1.109:8000"
        # addr = "http://autotest.zaxh.cn"
        url = f'{addr}/api/web/playwrightGridMsg/updateTestReport'
        result = requests.put(url, json=data).json()
        assert result["status"] == 1000
